package com.xy.smartsms.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.Toast;

import com.xy.smartsms.facade.AbsFacadeDoAction;

import org.json.JSONObject;

import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.util.PopupUtil;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;


/**
 * 实现动作执行类
 * Created by XIAOYUAN on 2016/11/24.
 */
public class XySdkAction extends AbsFacadeDoAction {
    private static final String TAG = "XySdkAction";
    public static boolean sIsLoadCompleted = false;
    private static final String DATABASE_AUTHORITY = "com.xy.bizportdemo";
    private static Uri URI_MESSAGE = Uri.parse("content://" + DATABASE_AUTHORITY + "/" + "tb_message");

    public void doExAction(Context ctx, String actionType, JSONObject data, Map extend) {
        Toast.makeText(ctx, "actionType=" + actionType + " __data=" + data, Toast.LENGTH_SHORT).show();
    }

    @Override
    public List<JSONObject> getReceiveMsgByReceiveTime(
            String phone,
            long startReceiveTime,
            long endReceiveTime,
            int limit) {

        List<JSONObject> jsonList = null;
        String[] projection = new String[]{"_id", "address", "body", "date"};
        Cursor cursor = null;
        try {
            StringBuffer sbSelection = new StringBuffer(" date > ");
            sbSelection.append(startReceiveTime);
            sbSelection.append("  and date < ");
            sbSelection.append(endReceiveTime);
            String[] selectionArgs = null;
            if (!StringUtils.isNull(phone)) {
                sbSelection.append(" and address = ? and block = ?");
                selectionArgs = new String[]{phone, String.valueOf(0)};
            }
            cursor = Constant.getContext().getContentResolver()
                    .query(URI_MESSAGE, projection, sbSelection.toString(), selectionArgs, "date desc LIMIT " + limit + " OFFSET 0");
            if (cursor != null && cursor.getCount() > 0) {
                jsonList = new ArrayList<JSONObject>();
                JSONObject smsJson = null;
                while (cursor.moveToNext()) {
                    smsJson = new JSONObject();
                    smsJson.put("msgId", cursor.getString(0));
                    smsJson.put("phone", cursor.getString(1));
                    smsJson.put("msg", cursor.getString(2));
                    smsJson.put("centerNum", "13800138000");
                    smsJson.put("smsReceiveTime", cursor.getString(3));
                    jsonList.add(smsJson);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
        }
        return jsonList;
    }

    /**
     * 回复短信
     *
     * @param context  上下文
     * @param msgId    短信消息id
     * @param phoneNum 号码
     * @param content  短信内容
     * @param extend   拓展参数
     */
    public void replySms(Context context, String msgId, String phoneNum, String content, Map<String, String> extend) {
        Toast.makeText(context, "phoneNum=" + phoneNum + "  msgId=" + msgId + " content=" + content, Toast.LENGTH_SHORT)
                .show();
    }

    private static String getContactNameByPhoneNumber(Context context, String address) {
        String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER};

        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    projection, // Which columns to return.
                    ContactsContract.CommonDataKinds.Phone.NUMBER + " = '" + address + "'", // WHERE
                    // clause.
                    null, // WHERE clause value substitution
                    null); // Sort order.

            if (cursor == null || cursor.getCount() <= 0) {
                return null;
            }

            cursor.moveToPosition(0);
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            String name = cursor.getString(nameFieldColumnIndex);
            return name;
        } catch (Throwable e) {
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    public String getContactName(Context context, String phoneNum) {
        // 调用开发者内部,依据号码获取联系人名称的方法
        return null;
    }

    /**
     * 标记短信已读
     *
     * @param context
     * @param msgId
     */
    public void markAsReadForDatabase(Context context, String msgId) {
        // 调用开发者内部短信标记为已读的api
    }

    /**
     * 打开短信原文进入会话
     *
     * @param context
     * @param phoneNum 短信号码
     * @param params   扩展参数 由调用towindow api方法时扩展参数传入 ,在此回调传回使用. msgId:短信消息id
     *                 smiIndex:双卡时,卡位 由调用towindow api方法时扩展参数传入
     */
    public void openSms(Context context, String phoneNum, Map<String, String> params) {
        // 调用开发者内部进入短信会话的api
    }

    /**
     * 发短信, 双卡需要指定卡位发短信.
     *
     * @param phoneNum 接收者号码
     * @param sms      短信内容
     * @param simIndex 卡位 此值需要在 调用parseMsgToPopupWindow方法的时候
     *                 在其extend函数中.加入simIndex的key将当前sim卡位传入. -1表示没有传入卡位
     * @param params   扩展参数
     */
    public void sendSms(Context context, String phoneNum, String sms, int simIndex, Map<String, String> params) {
        // 调用开发者内部发短信的api
        Toast.makeText(context, "发送短信", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void deleteMsgForDatabase(Context context, String msgId) {
        // TODO Auto-generated method stub

    }

    @Override
    public void openSmsDetail(Context context, String msgId, Map extend) {
        Toast.makeText(context, "打开短信原文 msgId=" + msgId, Toast.LENGTH_SHORT).show();
        Log.i("openSmsDetail", "打开短信原文 msgId=" + msgId);

    }

    @Override
    public String getIccidBySimIndex(int simIndex) {
        LogManager.i("MySdkDoAction", "getIccidBySimIndex simIndex===" + simIndex);
        return null;
    }

    @Override
    public void openMap(Context context, String title, String address, double lon, double lat) {
        if (StringUtils.isNull(address) && (lon <= 0 || lat <= 0)) {
            Toast.makeText(Constant.getContext(), "缺少参数，无法打开百度地图", Toast.LENGTH_SHORT).show();
            return;
        }

        // 搜索关键字
        address = address.replace(" ", ",").replace("（", ",").replace("(", ",").replace("，", ",").replace("）", "")
                .replace(")", "").replace("?", "").replace("&", "").replace("#", "").trim();

        // 地图查询参数
        String queryParam = null;

        // 存在搜索关键字
        if (!StringUtils.isNull(address)) {
            if (lon != 0 && lat != 0) {
                // 地图标点功能，调用该接口可调起PC或web地图，且在指定坐标点上显示点的名称和内容信息。
                queryParam = "marker?location=" + lat + "," + lon + "&title=" + title + "&content=" + address;
            } else {
                // 地址解析，调用该接口可以在调起百度地图时，当前页面显示地址对应的坐标点。
                queryParam = "geocoder?address=" + address;
            }

            // 没有搜索关键字，只有经纬度信息
        } else {
            // 反向地址解析，调用该接口可调起PC或Web百度地图，经过逆地理编码后，以标注形式显示位置和地址信息。
            // bd09ll表示百度经纬度坐标， gcj02表示经过国测局加密的坐标，wgs84表示gps获取的坐标。
            queryParam = "geocoder?location=" + lat + "," + lon + "&coord_type=gcj02";
        }

        // 已经安装了百度地图客户端
        if (super.checkHasAppName(context, "com.baidu.BaiduMap")) {
            try {
                Intent intent = Intent.getIntent("intent://map/" + queryParam
                        + "&src=xiaoyuan|多趣#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                // 启动百度地图客户端调用
                Constant.getContext().startActivity(intent);
                // 已经成功调用百度地图客户端直接返回
                return;
            } catch (URISyntaxException ex) {
                ex.printStackTrace();
            }
        }

        // 没有安装百度地图客户端或调用百度地图客户端失败，调用web百度地图查询
        try {
            String uriStr = "http://api.map.baidu.com/" + queryParam + "&output=html&src=xiaoyuan|多趣";
            JSONObject js = new JSONObject();
            js.put("url", uriStr);
            js.put("type", "WEB_URL");
            PopupUtil.startWebActivity(context, js, "WEB_URL", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重写定位
     */
    @Override
    public void getLocation(Context context, final Handler handler) {
//        LocationManager.getInstance().getLocation(new LocationManager.OnLocationReadyListener() {
//            @Override
//            public void onReady(XyLocationData data) {
//                try {
//                    if (data != null) {
//                        Message msg = handler.obtainMessage(AbsSdkDoAction.DO_SEND_MAP_QUERY_URL);
//                        Bundle bundle = new Bundle();
//                        bundle.putDouble("latitude", data.latitude);
//                        bundle.putDouble("longitude", data.longitude);
//                        msg.setData(bundle);
//                        msg.sendToTarget();
//                    }
//                } catch (Throwable t) {
//                    t.printStackTrace();
//                }
//            }
//        });
    }

    @Override
    public Drawable getDrawableByNumber(Context context, String number, Map<String, Object> extend) {
        return super.getDrawableByNumber(context, number, extend);
    }

    @Override
    public void openAppByAppName(Context context, String appName, String appDownUrl) {
        try {
            if (checkHasAppName(context, appName)) {
                PackageManager packageManager = context.getPackageManager();
                Intent intent = packageManager.getLaunchIntentForPackage(appName);
                setNewTaskIfNeed(context, intent);
                context.startActivity(intent);
            } else {
                if (!StringUtils.isNull(appDownUrl)) {
                    downLoadUrl(context, appDownUrl);
                } else {
                    Uri uri = Uri.parse("market://details?id=" + appName);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    String hwMarket = "com.huawei.appmarket";
                    if (checkHasAppName(context, hwMarket)) {
                        intent.setPackage(hwMarket);
                    }
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            }
        } catch (Throwable t) {
            Log.e(TAG, "openAppByAppName", t);
        }
    }

    @Override
    public void startWizardService(Context context, JSONObject jobj, Map map) {
        if (jobj == null) {
            return;
        }

        try {
            Log.i(TAG, "startWizardService: " + jobj);
            Class serviceMenuDialogClass = Class.forName("cn.com.xy.sms.sdk.ui.popu.widget.ServiceMenuDialog");
            Method method = serviceMenuDialogClass.getMethod("showMenuDialog", Context.class, JSONObject.class,
                    Map.class);
            method.invoke(serviceMenuDialogClass, context, jobj, map);
            // ServiceMenuDialog.showMenuDialog(context, jobj, map);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /* huangzhiqiang 20161128 begin */
    public Set<String> loadPublicNumbers(Context context) {
        Cursor cursor = null;
        try {
            cursor = Constant.getContext().getContentResolver()
                    .query(URI_MESSAGE, new String[]{"address"}, null, null, null);
            if (cursor == null || cursor.getCount() == 0) {
                return null;
            }

            Set hashSet = new HashSet();
            int addressIndex = cursor.getColumnIndex("address");
            while (cursor.moveToNext()) {
                String address = cursor.getString(addressIndex);
                if (!StringUtils.isNull(address)) {
                    String phoneNumber = StringUtils.replaceBlank(address);
                    phoneNumber = StringUtils.getPhoneNumberNo86(phoneNumber);
                    if (StringUtils.isNumber(phoneNumber) && !StringUtils.isPhoneNumber(phoneNumber)) {
                        hashSet.add(phoneNumber);
                    }
                }
            }
            return hashSet;
        } catch (Throwable e) {
            LogManager.w("XIAOYUAN", "loadPublicNumbers error:", e);
        } finally {
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
        }
        return null;
    }
    /* huangzhiqiang 20161128 end */

    /* huangzhiqiang 20161128 begin */
    public void onEventCallback(int eventType, Map<String, Object> extend) {
        super.onEventCallback(eventType, extend);
        switch (eventType) {
            case SDK_EVENT_INIT_COMPLETE:
                if (!isLoadCompleted()) {
                    setLoadCompleted();
                }

                sIsLoadCompleted = true;
                break;

            default:
                break;
        }
    }

    private static void setLoadCompleted() {
        try {
            Context context = Constant.getContext();
            SharedPreferences sp = context.getSharedPreferences("bizport_setting", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("load_completed", true);
            editor.apply();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static boolean isLoadCompleted() {
        try {
            Context context = Constant.getContext();
            SharedPreferences sp = context.getSharedPreferences("bizport_setting", Context.MODE_PRIVATE);
            return sp.getBoolean("load_completed", false);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }

    /* huangzhiqiang 20161128 end */
    public String getExtendConfig(int type, Map extend) {
        try {
            if (type == EXTEND_CONFIG_PARSE_MSG) {
                JSONObject extendCfg = new JSONObject();
                extendCfg.put("ref_basevalue", "true");//引用基础识别结果
                extendCfg.put("ALLOW_PERSONAL_MSG", "true");//支持私人转发
                extendCfg.put("isUseNewAction", "true");
                extendCfg.put("ENABLE_EIGENVALUE_PARSE", "true");
                extendCfg.put("DISABLE_BASE_PARSE", "false");
                //extendCfg.put("PUB_TYPE_CODE", mPublicInfoJson.optString("classifyCode"));

                return extendCfg.toString();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public void logError(String tag, String errorInfo, Throwable e) {
        Log.e(tag, errorInfo, e);
    }

    public void logInfo(String tag, String content, Map<String, Object> extend) {
    }

    @Override
    /**
     * 获取设备型号sim卡对应的运营商
     * @param simIndex -1:当前手机默认卡位; 0:卡1; 1:卡2
     * @param iccid
     * @return OPERATOR_UNKNOWN:未知, OPERATOR_CMCC:中移, OPERATOR_CUCC:中国联通, OPERATOR_CTCC:中国电信
     */
    public int getModelOperator(int simIndex, String iccid) {
        return OPERATOR_CMCC;
    }

    @Override
    public String getConfig(int type, Map extend) {
        String res = null;
        switch (type) {
            case CONFIG_WEB_ACTIVITY_CLASS:
                res = "cn.cmcc.online.smsapi.ui.web.SdkWebActivity";
                break;

            case CONFIG_NEARBY_ACTIVITY_CLASS:
                res = "cn.cmcc.online.smsapi.ui.web.NearbyPointList";
                break;

            case CONFIG_UI_CONFIG_CLASS:
                res = "cn.cmcc.online.smsapi.ui.web.data.MenuData";
                break;

            default:
                res = super.getConfig(type, extend);
                break;

        }

        return res;
    }

    @Override
    public void startWebActivity(Context context, Intent intent) {
        InstrumentationWrapper.replaceInstrumentation((Activity) context);
        super.startWebActivity(context, intent);
    }
}
